package com.hxzy.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.hxzy.dto.OrderDTO;
import com.hxzy.dto.OrderSearch;
import com.hxzy.entity.AddressBook;
import com.hxzy.entity.OrderDetail;
import com.hxzy.entity.Orders;
import com.hxzy.entity.ShoppingCart;
import com.hxzy.mapper.OrdersMapper;
import com.hxzy.service.AddressBookService;
import com.hxzy.service.OrderDetailService;
import com.hxzy.service.OrdersService;
import com.hxzy.service.ShoppingCartService;
import com.hxzy.util.SSMThreadLocal;
import com.hxzy.vo.ContamerLoginVO;
import com.hxzy.vo.OrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * 订单信息业务逻辑实现
 *
 * @author tonneyyy
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<Orders,Long> implements OrdersService {

    private OrdersMapper ordersMapper;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    public void setOrdersMapper(OrdersMapper ordersMapper) {
        this.ordersMapper = ordersMapper;
        super.setMyBatisBaseDao(ordersMapper);
    }

    @Override
    public List<OrderVO> orderPage(OrderSearch orderSearch) {
        List<OrderVO> arr=new ArrayList<>();

        List<Orders> ordersList=this.ordersMapper.search(orderSearch);
        for(Orders orders: ordersList){
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            //查询订单明细
            List<OrderDetail> orderDetails = this.orderDetailService.findByOrderId(orders.getId());
            orderVO.setOrderDetails(orderDetails);

            //放到集合中去
            arr.add(orderVO);
        }
        return arr;
    }

    /**
     * 下单
     * @param orderDTO
     * @param list
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long submit(OrderDTO orderDTO, List<ShoppingCart> list) {
        ContamerLoginVO contamerLoginVO = SSMThreadLocal.contamerLoginVOThreadLocal.get();

        //先创建订单
        Orders  orders=new Orders();
        //商家id
        orders.setMid(orderDTO.getMid());
        //用户id
        orders.setUserId(new Long(contamerLoginVO.getId()));
        //下单时间
        orders.setOrderTime(new Date());
        //备注
        orders.setRemark(orderDTO.getRemark());
        //支付类型
        orders.setPayMethod(orderDTO.getPayMethod());
        //收货地址id
        orders.setAddressBookId(orderDTO.getAddressBookId());
        //订单状态，待付款
        orders.setStatus(1);

        //收货地址
        AddressBook addressBook = this.addressBookService.selectByPrimaryKey(orderDTO.getAddressBookId());

       String address= StrUtil.format("{}{}{}{}", addressBook.getProvinceName(),addressBook.getCityName(),addressBook.getDistrictName(),addressBook.getDetail());
       //收货地址
        orders.setAddress(address);
        //收货人电话
        orders.setPhone( addressBook.getPhone());
        //收货人姓名
        orders.setConsignee(addressBook.getConsignee());
        //下单人的用户名
        orders.setUserName(contamerLoginVO.getUserName());

        //生成订单号  uuid(不建议使用，没有任何规律), 雪花算法(当前时间为基准来计算的,google提出来的算法)
        long orderId= IdUtil.getSnowflake().nextId();
        orders.setNumber(orderId+"");
        //汇总金额
        AtomicReference<Double> money= new AtomicReference<>(0.0);
        list.stream().forEach(p-> {
            money.updateAndGet(v -> v + p.getNumber() * p.getAmount().doubleValue());
        });

        orders.setAmount( new BigDecimal(money.get()));

        //新增订单
        int result = this.ordersMapper.insert(orders);

        //再创建订单明细表
        if(result>0){
            //循环遍历购物车有多少笔产品
            list.stream().forEach(p-> {
                //订单明细
                OrderDetail  orderDetail=new OrderDetail();
                orderDetail.setNumber(p.getNumber());
                orderDetail.setAmount( p.getAmount());
                orderDetail.setMid( p.getEnterpriseId());
                //订单ID
                orderDetail.setOrderId(orderId);
                orderDetail.setDishFlavor(p.getDishFlavor());
                orderDetail.setDishId(p.getDishId());
                orderDetail.setImage(p.getImage());
                orderDetail.setName( p.getName());

                this.orderDetailService.insert(orderDetail);
            });

            //删除购物车的信息
            List<Long> collect = list.stream().map(ShoppingCart::getId).collect(Collectors.toList());
            for(Long id : collect){
                this.shoppingCartService.deleteByPrimaryKey(id);
            }
        }

        return orderId;
    }

    /**
     * 根据订单号查询数据
     * @param orderId
     * @return
     */
    @Override
    public Orders selectByOrderId(Long orderId) {
        return this.ordersMapper.selectByOrderId(orderId);
    }

    /**
     * 更新订单状态
     * @param orderId
     * @param payTime
     * @return
     */
    @Override
    public int updateByOrderId(Long orderId, String payTime) {
        return this.ordersMapper.updateByOrderId(orderId,payTime);
    }
}